package com.trytech.mongoocrawler.client;

import com.trytech.mongoocrawler.client.cache.redis.CrawlerRedisSession;
import com.trytech.mongoocrawler.client.cache.redis.RedisClient;
import com.trytech.mongoocrawler.client.cache.redis.RedisKeyGenerator;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 爬虫运行环境
 */
public class CrawlerContext {
    private ConcurrentHashMap<String, CrawlerSession> sessionMap = new ConcurrentHashMap<String,CrawlerSession>();
    private static CrawlerConfig config;
    public void start(){
        System.out.println("启动容器...");
        //加载配置文件
        try {
            config = CrawlerConfig.newInstance(System.getProperty("user.dir")+ File.separator+"config.properties");
        } catch (IOException e) {
            destory();
            e.printStackTrace();
            return;
        }
        //获取url存储在哪里
        CrawlerSession initSession = null;
        if(config.getUrlStoreMode().equals(CrawlerConfig.URL_STORE_MODE.REDIS)){
            RedisClient client = RedisClient.getClient(config.getRedisIp(),config.getRedisPort(),null);
            initSession= new CrawlerRedisSession(this,client, RedisKeyGenerator.getKey());
        }else{
            String[] startUrls = config.getStartUrls();
            //注册初始session
            initSession= new CrawlerSession(this,startUrls);
        }
        registerSession(initSession);
        for(CrawlerSession session : sessionMap.values()){
            session.start();
        }
    }

    public void destory(){
        sessionMap.clear();
        sessionMap = null;
    }

    public void removeSession(String sessionId){
        sessionMap.remove(sessionId);
    }

    public void registerSession(CrawlerSession session){
        sessionMap.put(session.getSessionId(),session);
    }

    public CrawlerConfig getConfig(){
        return config;
    }
}
